import { cps as cps1 } from '@/utils/callProxyService'
import { cps as cps2 } from '@/utils/callProxyService2'
import { getValueByChain, deepCopy } from '@/utils'
import { pagePermission } from '@/api/pagePermission'
import { sort } from '@/utils/sort'

function getCps(state) {
  if (state.user?.userCache?.callPlatform === '02') {
    console.log('cps2', cps2)
    return cps2
  } else {
    console.log('cps1', state, cps1)
    return cps1
  }
}

// 时间相关
const ratioSecond = 1000
const ratioMinute = 60 * ratioSecond
const ratioHour = 60 * ratioMinute

let timerid = null // 通话时长计时器id
let startTime = 0 // 开始通话时间点
// 开始计时
function startTimer(callback) {
  if (timerid) {
    stopTimer()
  }
  startTime = new Date().getTime()
  timerid = setInterval(() => {
    // eslint-disable-next-line prefer-const
    let diff = new Date().getTime() - startTime
    const hour = Math.floor(diff / ratioHour)
      .toString()
      .padStart(2, '0')
    const minute = Math.floor((diff % ratioHour) / ratioMinute)
      .toString()
      .padStart(2, '0')
    const second = Math.floor((diff % ratioMinute) / ratioSecond)
      .toString()
      .padStart(2, '0')
    callback(`${hour}:${minute}:${second}`)
  }, 300)
}
// 停止计时
function stopTimer() {
  clearInterval(timerid)
  startTime = 0
}
const state = {
  agentid: '', // 坐席工号
  phonenum: '', // 分机号
  interval: 600, // 轮询时间间隔
  sign: false, // 签入
  free: false, // 空闲
  // 整理中
  work: false, // 工作中
  // 通话中状态
  talk: false, // 通话中
  hold: false, // 保持
  mute: false, // 静音
  answer: false, // 应答
  mpty: false, // 三方通话
  // 响铃
  alert: false, // 响铃
  clientAlert: false, // 客户端响铃

  callTel: '', // 当前接通电话
  callid: '', // 当前通话id
  callData: {}, // 当前随路数据
  duration: '00:00:00', // 通话时长

  agentInfo: {}, // 当前坐席信息
  skillList: [], // 当前坐席可用的技能组
  queueSize: 0, // 排队人数
  // 开始通话时间
  startCallTime: null,
  // 坐席状态
  // 座席当前状态 0话务员未签入。1话务员空闲。2预占用状态。
  // 3占用状态。4应答状态。5通话状态。6工作状态。7示忙状态。
  // 8请假休息。9学习态。10调整态。
  statusList: [
    {
      value: '',
      label: '全部'
    },
    {
      value: 0,
      label: '未签入'
    },
    {
      value: 1,
      label: '空闲'
    },
    {
      value: 2,
      label: '预占用'
    },
    {
      value: 3,
      label: '占用'
    },
    {
      value: 4,
      label: '应答'
    },
    {
      value: 5,
      label: '通话'
    },
    {
      value: 6,
      label: '工作'
    },
    {
      value: 7,
      label: '示忙'
    },
    {
      value: 8,
      label: '休息'
    },
    {
      value: 9,
      label: '学习'
    },
    {
      value: 10,
      label: '调整'
    }
  ],
  // 历史通话记录
  // {
  //   callTell:'',// 号码
  //   callid:'', //通话id
  //   callData:{}, //随路数据
  //   recordId:'', //通话记录id
  // }
  recordList: {}, // callid作为key
  callBarButtonList: [], // 话务条按钮列表
  isCallOut: false, // 是否是呼出
  callOutRecordId: '', // 当前外呼通话记录id
  prefix: '', // 当前呼出前缀
  // 归属地
  callAddress: '', // 来电归属地
  // 外呼真实号码
  realCallOutTel: ''
}
export const mutations = {
  // 更新坐席工号
  SET_AGENT_ID(state, v) {
    state.agentid = v
  },
  // 更新分机号
  SET_PHONE_NUM(state, v) {
    state.phonenum = v
  },
  // 当前通话id
  SET_CALL_ID(state, v) {
    state.callid = v
  },
  // 当前接通电话
  SET_CALL_TEL(state, v) {
    if (!state.talk) {
      state.callTel = v
    }
  },
  // 外呼真实号码
  SET_REAL_CALL_OUT_TEL(state, v) {
    // if (!state.talk) {
    state.realCallOutTel = v
    // }
  },
  SET_CALL_DATA(state, v) {
    state.callData = v
  },
  // 通话时长
  SET_DURATION(state, v) {
    state.duration = v
  },
  // 更新当前坐席信息
  SET_AGENT_INFO(state, v) {
    state.agentInfo = v
  },
  // 更新坐席状态
  SET_AGENT_STATE(state, v) {
    state[v.key] = v.value
  },
  // 更新技能组
  SET_SKILL_LIST(state, v) {
    state.skillList = v
  },
  // 更新排队数据
  SET_QUEUE_SIZE(state, v) {
    state.queueSize = v
  },
  // 更新\删除 历史通话记录
  SET_RECORD_LIST(state, v) {
    if (v === undefined || v.callid === undefined) return
    const recordList = deepCopy(state.recordList)
    if (typeof v === 'string') {
      delete recordList[v]
    } else {
      const cd = v.callData || {}
      const ocd = (recordList[v.callid] || {}).callData || {}
      recordList[v.callid] = Object.assign(recordList[v.callid] || {}, v)
      recordList[v.callid].callData = Object.assign(ocd, cd)
    }
    state.recordList = recordList
  },
  // 开始通话时间
  SET_STATE_CALL_TIME(state, v) {
    if (v === undefined) {
      state.startCallTime = new Date().getTime()
    } else {
      state.startCallTime = v
    }
  },
  // 清理数据
  SET_CLEAR_DATA(state) {
    // state.agentid = '' // 坐席工号
    // state.phonenum = '' // 分机号
    state.interval = 600 // 轮询时间间隔
    state.sign = false // 签入
    state.free = false // 空闲
    // 整理中
    state.work = false // 工作中
    // 通话中状态
    state.talk = false // 通话中
    state.hold = false // 保持
    state.mute = false // 静音
    state.answer = false // 应答
    state.mpty = false // 三方通话
    // 响铃
    state.alert = false // 响铃
    state.clientAlert = false // 客户端响铃

    state.callTel = '' // 当前接通电话
    state.realCallOutTel = '' // 外呼真实号码
    state.callid = '' // 当前通话id
    state.callData = {} // 当前随路数据
    state.duration = '00:00:00' // 通话时长

    state.agentInfo = {} // 当前坐席信息
    state.skillList = [] // 当前坐席可用的技能组
    state.queueSize = 0 // 排队人数
    state.recordList = {} // callid作为key
    // state.callBarButtonList = []
    state.callOutRecordId = ''
    state.isCallOut = false
    state.callAddress = ''
    state.prefix = ''
    state.startCallTime = null
  },
  // 更新话务条按钮数据
  SET_CALL_BAR_BUTTON_LIST(state, v) {
    state.callBarButtonList = v
  },
  // 更新呼出状态
  SET_IS_CALL_OUT(state, v) {
    state.isCallOut = v
  },
  // 更新外呼通话记录id
  SET_CALL_OUT_RECORD_ID(state, v) {
    state.callOutRecordId = v
  },
  // 归属地
  SET_CALL_ADDRESS(state, v) {
    state.callAddress = v
  },
  // 前缀
  SET_CALL_PREFIX(state, v) {
    state.prefix = v
  }
}

const getters = {
  agentid: state => { // FIXME:删除
    // if (process.env.NODE_ENV === 'development') {
    //   return '50004'
    // } else {
    return state.agentid
    // }
  }, // FIXME:线上改回原来的代码
  phonenum: state => state.phonenum,
  callAddress: state => state.callAddress,
  agentInfo: state => state.agentInfo,
  interval: state => state.interval,
  // 坐席状态
  agentState: state => {
    return {
      sign: state.sign, // 签入签出
      free: state.free, // 空闲
      // 整理中
      work: state.work, // 工作中
      // 通话中状态
      talk: state.talk, // 通话中
      hold: state.hold, // 保持
      mute: state.mute, // 静音
      answer: state.answer, // 应答
      mpty: state.mpty, // 三方通话
      // 响铃
      alert: state.alert, // 响铃
      clientAlert: state.clientAlert // 客户端响铃
    }
  },
  // 通话信息
  callInfo: state => {
    return {
      callTel: state.callTel,
      realCallOutTel: state.realCallOutTel, // 外呼真实号码
      callid: state.callid,
      duration: state.duration,
      callData: state.callData,
      callOutRecordId: state.callOutRecordId,
      prefix: state.prefix,
      isCallOut: state.isCallOut,
      startCallTime: state.startCallTime
    }
  },
  // 通话时长
  startCallTime: state => state.startCallTime,

  skillList: state => state.skillList,
  queueSize: state => state.queueSize,
  statusList: state => state.statusList,
  recordList: state => state.recordList,
  isCallOut: state => state.isCallOut,
  callBarButtonList: state => {
    return sort(state.callBarButtonList, (a, b) => {
      return b.sort < a.sort
    }).map(e => e.buttonCode)
  }
}

const actions = {
  // 计算通话时长
  computedDuration({ commit }) {
    startTimer(v => {
      commit('SET_DURATION', v)
    })
  },
  // 停止计算通话时长
  stopDuration(commit) {
    stopTimer()
  },
  // 获取坐席信息
  async queryAgentInfoByWorkNo({ commit, state, rootState }, agentid) {
    return await getCps(rootState).queryAgentInfoByWorkNo(agentid).then(e => {
      commit('SET_AGENT_INFO', e.data)
      // 更新坐席状态
      // 座席当前状态 0话务员未签入。1话务员空闲。2预占用状态。
      // 3占用状态。4应答状态。5通话状态。6工作状态。7示忙状态。
      // 8请假休息。9学习态。10调整态。
      return e
    })
  },
  // 获取技能组
  async queryTotalSkills({ commit, state, rootState }, workno) {
    return await getCps(rootState).queryTotalSkills(workno).then(res => {
      commit('SET_SKILL_LIST', res.data.skill)
      return res
    })
  },
  // 获取排队人数
  async voiceSkillStatistic({ commit, state, rootState }) {
    // return await cps.voiceSkillStatistic().then(res => {
    //   const skillid = new Set()
    //   for (const item of state.agentInfo.skilllist) {
    //     skillid.add(item.id)
    //   }
    //   let num = 0
    //   for (const l of res.data.statisticList) {
    //     if (skillid.has(l.skillId)) {
    //       num += l.queueSize
    //     }
    //   }
    //   commit('SET_QUEUE_SIZE', num)
    // })
    const list = state.agentInfo.skilllist
    let all = []
    if (list instanceof Array) {
      all = list.map(e => getCps(rootState).queryQueueInfo(e.id))
    }
    return await Promise.all(all).then(res => {
      const sum = res.reduce((pre, curr) => pre + curr.data.waitcallinfo.length, 0)
      commit('SET_QUEUE_SIZE', sum)
    })
  },
  // 更新通话信息
  callerInfo({ commit }, res) {
    const content = getValueByChain(res, 'data.content', {})
    commit('SET_CALL_ID', content.callid)
    const caller = getValueByChain(content, 'caller', '')
    const called = getValueByChain(content, 'called', '')
    const feature = getValueByChain(content, 'feature', '')
    if (feature === '7') {
      commit('SET_CALL_TEL', called)
    } else {
      commit('SET_CALL_TEL', caller)
    }
  },
  // 获取话务条按钮列表
  getCallBarButtonList({ commit }, menu) {
    let menuCode = ''
    for (const m of menu) {
      if (m.url === '/index') {
        menuCode = m.menuCode
        break
      }
    }
    if (menuCode === '') return
    pagePermission(menuCode, 'huawutiao').then(res => {
      commit('SET_CALL_BAR_BUTTON_LIST', res.data.groovyList || [])
    })
  }
}

export default {
  state,
  mutations,
  getters,
  actions
}
